/*
 *  NxtDeviceBrowser.mm
 *  NXTFace
 *
 *  Created by David Giovannini on 8/23/06.
 *  Copyright 2006 Software by Jove. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 */

#import "NxtDeviceBrowser.h"
#import "NxtDevice.h"
#import "NxtDocument.h"

#include "SBJ/NXT/DeviceBrowser.h"
#include "SBJ/NXT/Device.h"
#include "SBJ/NXT/Command.h"
#include "SBJ/NXT/CommandTraits.h"

@implementation NxtDeviceBrowser

- (id) init
{
	if(self = [super init])
	{
		[[NSNotificationCenter defaultCenter] addObserver:self
			selector:@selector(applicationWillTerminate:)
			name:@"NSApplicationWillTerminateNotification" object:NSApp];
			
		m_browser = new SBJ::NXT::DeviceBrowser;
		
		m_documents = [ [ NSMutableDictionary alloc ] init ];
		
		m_search = [ [ NSMutableDictionary alloc ] init ];
		
		m_count = 0;
	}
	return self;
}

// dealloc is not always called!
// the NXT hardware wants to be disconnected
- (void)applicationWillTerminate:(NSNotification *)notification
{
	delete m_browser;
	m_browser = 0;
}

- (void) dealloc
{
	delete m_browser;
	[ super dealloc ];
	m_browser = 0;
}

- (void) awakeFromNib
{
	[ self scan:self ];
}

// Scripability

- (BOOL)application:(NSApplication *)sender delegateHandlesKey:(NSString *)key
{
//    if ([key isEqual:@"Devices"]) {
        return YES;
//    } else {
//        return NO;
//    }
}

- (void)scripterSaysScan:(NSScriptCommand*)command
{
	[ self scan: command ];
}

-(int) countOfDevices
{
	return m_count;
}

-(NxtDevice*) valueInDevicesWithName: (NSString*)name
{
	return [ m_search objectForKey: name ];
}

// Accessors

-(NSArray*) Devices
{
	return [ m_search allValues ];
}

// Commands

- (void) scan:(id)sender
{
	m_count = 0;
	m_browser->scan();
	for ( int i = 0; i < m_browser->getCount(); ++i )
	{
		SBJ::NXT::Device* rawDevice = m_browser->getDevice( i );
		if ( rawDevice )
		{
			NSString* sessionName = [ NSString stringWithCString: rawDevice->getSessionName().c_str() ];
			NxtDevice* device = [ m_search objectForKey: sessionName ];
			if ( device == nil )
			{
				++m_count;
				device = [ [ NxtDevice alloc ] initWithDevice: rawDevice ];
				[ m_search setValue: device forKey: sessionName ];
				[ m_search setValue: device forKey: [ device Name ] ];
				[ m_devices addObject: device ];
			}
		}
	}
}

- (BOOL)validateMenuItem:(NSMenuItem *)item
{
	int row = [ m_devices selectionIndex ];
	return ( row >= 0 ? YES : NO );
}

- (void) control:(id)sender
{
	[ self newDocument: sender ];
}

- (IBAction)newDocument:(id)sender
{
	NxtDevice* device = [ [ m_devices selectedObjects ] objectAtIndex: 0 ] ;

	NSString* sessionName = [ device SessionName ];
	NxtDocument* doc = [ m_documents objectForKey: sessionName ];
	if ( doc )
	{
		[ doc showWindows ];
	}
	else
	{
		NSError* error = 0;
		NxtDocument* doc = [ self openUntitledDocumentAndDisplay:YES error:&error ];
		[ doc setDevice: device ];
		[ m_documents setValue: doc forKey: sessionName ];
	}
}

- (void)removeDocument:(NSDocument *)document
{
	[ m_documents removeObjectForKey: [ [ (NxtDocument*)document Device ] SessionName ] ];
}

@end